package cn.wit.summit.chwan.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.MakeMoneyV4Adapter;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.request.MakeMoneyIndexV3Request;
import cn.wit.summit.chwan.models.response.GetGameDetailShareDataResponse;
import cn.wit.summit.chwan.models.response.MakeMoneyIndexResponseV3;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.MakeMoneyRankingIndexActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.DigitalChangeTextView;
import cn.wit.summit.chwan.widgets.MessageDialog;
import cn.wit.summit.chwan.widgets.ShareBottomDialog;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/8/28.
 */

public class MakeMoneyV3Fragment extends BaseFragment {

    @Bind(R.id.todayIncomeTv)
    DigitalChangeTextView todayIncomeTv;
    @Bind(R.id.balanceTv)
    TextView balanceTv;
    @Bind(R.id.makeMoneyTodayMoneyTv)
    TextView makeMoneyTodayMoneyTv;
    @Bind(R.id.makeMoneyTopLeftLl)
    LinearLayout makeMoneyTopLeftLl;
    @Bind(R.id.makeMoneyYestodayPeopleTv)
    TextView makeMoneyYestodayPeopleTv;
    @Bind(R.id.makeMoneyTopRightLl)
    LinearLayout makeMoneyTopRightLl;
    @Bind(R.id.creditScoreTv)
    TextView creditScoreTv;
    @Bind(R.id.creditScoreRl)
    RelativeLayout creditScoreRl;
    @Bind(R.id.receiveBt)
    Button receiveBt;
    @Bind(R.id.understandBt)
    Button understandBt;
    @Bind(R.id.makeMoneyReceiveStep1Iv)
    ImageView makeMoneyReceiveStep1Iv;
    @Bind(R.id.makeMoneyReceiveStep1View)
    View makeMoneyReceiveStep1View;
    @Bind(R.id.makeMoneyReceiveStep2Iv)
    ImageView makeMoneyReceiveStep2Iv;
    @Bind(R.id.makeMoneyReceiveStep2View)
    View makeMoneyReceiveStep2View;
    @Bind(R.id.makeMoneyReceiveStep3Iv)
    ImageView makeMoneyReceiveStep3Iv;
    @Bind(R.id.makeMoneyReceiveStep3View)
    View makeMoneyReceiveStep3View;
    @Bind(R.id.makeMoneyReceiveStep4Iv)
    ImageView makeMoneyReceiveStep4Iv;
    @Bind(R.id.makeMoneyReceiveStep1Tv)
    TextView makeMoneyReceiveStep1Tv;
    @Bind(R.id.makeMoneyReceiveStep2Tv)
    TextView makeMoneyReceiveStep2Tv;
    @Bind(R.id.makeMoneyReceiveStep3Tv)
    TextView makeMoneyReceiveStep3Tv;
    @Bind(R.id.makeMoneyReceiveStep4Tv)
    TextView makeMoneyReceiveStep4Tv;
    @Bind(R.id.bottomLl)
    LinearLayout bottomLl;
//    @Bind(R.id.makeMoneyGv)
//    MyGridView makeMoneyGv;

    private List<MakeMoneyIndexResponseV3.ContributionListBean> funList = new ArrayList<>();
    private MakeMoneyV4Adapter adapter;

    private RetrofitManager retrofitManager;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_make_money_v4, container, false);
        ButterKnife.bind(this, view);

//        understandBt.setEnabled(false);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        initView();
        return view;
    }

    private void initView() {
//        adapter = new MakeMoneyV4Adapter(getActivity(), funList);
//        makeMoneyGv.setAdapter(adapter);
//        makeMoneyGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                ToastUtils.getInstance(getContext()).showToastSystem("" + (position + 1));
//            }
//        });
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e("tbl>>>Recommend>>onResume()");
        getMoneyRanking();
        getUserinfo();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.e("tbl>>>Recommend>>setUserVisibleHint");
        if (getActivity() != null && isVisibleToUser) {
            getMoneyRanking();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (todayIncomeTv.getValue() > 0f) {
                todayIncomeTv.runView();
            }
            getUserinfo();
            getMoneyRanking();
        }
    }

    private void getMoneyRanking() {
        int uid = 0;
        if (AccountUtil.getInstance().getAccountData() != null) {
            uid = AccountUtil.getInstance().getUid();
        }
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            apiLogin.getMakeMoneyIndexV3(uid, AccountUtil.getInstance().getToken()).enqueue(new MyCallback<ResponseBase<MakeMoneyIndexResponseV3>>() {
                @Override
                public void onSuccess(ResponseBase<MakeMoneyIndexResponseV3> model) {
                    MakeMoneyIndexResponseV3 data = model.getData_info();
                    upUiView(data);
                }

                @Override
                public void onFailure(int code, String msg) {
                    showToast(msg);
                }
            });
        }
    }

    private void upUiView(MakeMoneyIndexResponseV3 data) {

//        todayIncomeTv.setText(data.getTodayIncome() + "");
        todayIncomeTv.setValue(data.getTodayIncome());
        todayIncomeTv.runView();
        balanceTv.setText("余额 " + data.getWallet() + " 元");
        makeMoneyTodayMoneyTv.setText("" + data.getTodayReward());
        makeMoneyYestodayPeopleTv.setText(data.getYesterdayRank() + "");
        creditScoreTv.setText(data.getCredit() + "");

        if (data.getContributionList() != null && data.getContributionList().size() > 0) {
            setFunData(data.getContributionList());
        }

//        data.setRewardStatus(1);
        if (data.getRewardStatus() == 0) {
            receiveBt.setText(getActivity().getResources().getString(R.string.makemoney_t18_str));
            receiveBt.setEnabled(false);
        } else if (data.getRewardStatus() == 1) {
            receiveBt.setText(getActivity().getResources().getString(R.string.makemoney_t7_str));
            receiveBt.setEnabled(true);
        } else if (data.getRewardStatus() == 2) {
            receiveBt.setText(getActivity().getResources().getString(R.string.makemoney_t19_str));
            receiveBt.setEnabled(false);
        }

        setStatusLine(data.getCreditSchdule());
    }

    private void setStatusLine(int rewardStatus) {
        makeMoneyReceiveStep1Iv.setImageResource(R.drawable.makemoney_receive_three);
        makeMoneyReceiveStep2Iv.setImageResource(R.drawable.makemoney_receive_three);
        makeMoneyReceiveStep3Iv.setImageResource(R.drawable.makemoney_receive_three);
        makeMoneyReceiveStep4Iv.setImageResource(R.drawable.makemoney_receive_three);

        makeMoneyReceiveStep1View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D8D8D8));
        makeMoneyReceiveStep2View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D8D8D8));
        makeMoneyReceiveStep3View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D8D8D8));

        makeMoneyReceiveStep1Tv.setTextColor(getActivity().getResources().getColor(R.color.color_686868));
        makeMoneyReceiveStep2Tv.setTextColor(getActivity().getResources().getColor(R.color.color_686868));
        makeMoneyReceiveStep3Tv.setTextColor(getActivity().getResources().getColor(R.color.color_686868));
        makeMoneyReceiveStep4Tv.setTextColor(getActivity().getResources().getColor(R.color.color_686868));

        if (rewardStatus == 0) {
            makeMoneyReceiveStep1Iv.setImageResource(R.drawable.makemoney_receive_two);
            makeMoneyReceiveStep1Tv.setTextColor(getActivity().getResources().getColor(R.color.color_black));
        } else if (rewardStatus == 1) {
            makeMoneyReceiveStep1Iv.setImageResource(R.drawable.makemoney_receive_one);
            makeMoneyReceiveStep2Iv.setImageResource(R.drawable.makemoney_receive_two);
            makeMoneyReceiveStep1View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D2C597));
            makeMoneyReceiveStep2Tv.setTextColor(getActivity().getResources().getColor(R.color.color_black));
        } else if (rewardStatus == 2) {
            makeMoneyReceiveStep1Iv.setImageResource(R.drawable.makemoney_receive_one);
            makeMoneyReceiveStep2Iv.setImageResource(R.drawable.makemoney_receive_one);
            makeMoneyReceiveStep3Iv.setImageResource(R.drawable.makemoney_receive_two);
            makeMoneyReceiveStep1View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D2C597));
            makeMoneyReceiveStep2View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D2C597));
            makeMoneyReceiveStep3Tv.setTextColor(getActivity().getResources().getColor(R.color.color_black));
        } else if (rewardStatus == 3) {
            makeMoneyReceiveStep1Iv.setImageResource(R.drawable.makemoney_receive_one);
            makeMoneyReceiveStep2Iv.setImageResource(R.drawable.makemoney_receive_one);
            makeMoneyReceiveStep3Iv.setImageResource(R.drawable.makemoney_receive_one);
            makeMoneyReceiveStep4Iv.setImageResource(R.drawable.makemoney_receive_two);
            makeMoneyReceiveStep1View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D2C597));
            makeMoneyReceiveStep2View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D2C597));
            makeMoneyReceiveStep3View.setBackgroundColor(getActivity().getResources().getColor(R.color.color_D2C597));
            makeMoneyReceiveStep4Tv.setTextColor(getActivity().getResources().getColor(R.color.color_black));
        }
    }

    private void setFunData(List<MakeMoneyIndexResponseV3.ContributionListBean> myInfo) {
//        makeMoneyGv.setFocusable(false);
//        funList.clear();
//        funList.addAll(myInfo);
//        adapter.notifyDataSetChanged();
//        makeMoneyGv.setFocusable(false);

        bottomLl.removeAllViews();
        for (int i=0;i<myInfo.size();i++) {
            View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_makemoney_fun_v4_view, null);
            SimpleDraweeView itemFunIv = itemView.findViewById(R.id.itemFunIv);
            TextView itemFunTitleTx = itemView.findViewById(R.id.itemFunTitleTx);
            TextView itemFunMoneyTx = itemView.findViewById(R.id.itemFunMoneyTx);
            LinearLayout itemFunRuleLl = itemView.findViewById(R.id.itemFunRuleLl);
            View itemFunLine = itemView.findViewById(R.id.itemFunLine);

            MakeMoneyIndexResponseV3.ContributionListBean temp = myInfo.get(i);
            itemFunIv.setImageURI(temp.getIcon());
            itemFunMoneyTx.setText(temp.getMoney()+"元/个");
            itemFunTitleTx.setText(temp.getTitle());
            itemFunRuleLl.removeAllViews();
            List<String> listStr = temp.getDetail();
            for (int j=0;j<listStr.size();j++) {
                View itemTView = LayoutInflater.from(getActivity()).inflate(R.layout.item_makemoney_fun_item_v4_view, null);
                TextView num = itemTView.findViewById(R.id.itemFunNumTx);
                TextView content = itemTView.findViewById(R.id.itemFunContentTx);

                num.setText((j+1)+"、");
                content.setText(listStr.get(j));
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                        , ViewGroup.LayoutParams.WRAP_CONTENT);
                if (j!=0) {
                    params.topMargin = (int) getResources().getDimension(R.dimen.wdp12);
                } else {
                    params.topMargin = 0;
                }
                itemTView.setLayoutParams(params);
                itemFunRuleLl.addView(itemTView);
            }

            bottomLl.addView(itemView);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void setSelectIndex() {
    }

    @OnClick({R.id.balanceTv, R.id.makeMoneyTopLeftLl, R.id.makeMoneyTopRightLl, R.id.creditScoreRl
            , R.id.receiveBt, R.id.understandBt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.balanceTv:
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(getActivity(), MyApplication.cfgPlug.getValue_wallet_url_v2());
                break;
            case R.id.makeMoneyTopLeftLl:
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                String url = RpcConstant.forumLoginRootUrl + "static_v3/index.html";
                IntentUtil.getInstance().goShareWebActivity(getActivity(), url);
                break;
            case R.id.makeMoneyTopRightLl:
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                startActivity(new Intent(getActivity(), MakeMoneyRankingIndexActivity.class));
                break;
            case R.id.creditScoreRl:
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                String url2 = RpcConstant.forumLoginRootUrl + "static_v3/credit.html";
                IntentUtil.getInstance().goShareWebActivity(getActivity(), url2);
                break;
            case R.id.receiveBt:
                getRewardV3();
                break;
            case R.id.understandBt:
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                getShareData();
                break;
        }
    }

    private void getShareData() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                int uid = AccountUtil.getInstance().getUid();
                String token = AccountUtil.getInstance().getToken();
                showLoading("获取分享数据中...");
                apiLogin.getShareDataPersonal(uid, token).enqueue(new MyCallback<ResponseBase<GetGameDetailShareDataResponse>>() {
                    @Override
                    public void onSuccess(ResponseBase<GetGameDetailShareDataResponse> model) {
                        GetGameDetailShareDataResponse response = model.getData_info();
                        cancelLoading();
                        if (response!=null && response.getRecord()!=null) {
                            String shareUrl = response.getRecord().getSharePicURL();
                            if (!StringUtils.isEmpty(shareUrl)) {
                                WindowManager windowManager = getActivity().getWindowManager();
                                Display display = windowManager.getDefaultDisplay();
                                new ShareBottomDialog(getActivity(), display.getWidth(), shareUrl, 1).show();
                            } else {
                                showToast("分享数据获取失败，请稍后再试！");
                            }
                        } else {
                            showToast("分享数据获取失败，请稍后再试！");
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        cancelLoading();
                        showToast(msg);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            showToast("网络出错，请稍后再试！");
        }
    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                            }
                            ToastUtils.getInstance(getActivity()).showToastSystem(msg);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void getRewardV3() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.getRewardV3(uid, token).enqueue(new MyCallback<ResponseBase<MakeMoneyIndexResponseV3>>() {
                        @Override
                        public void onSuccess(ResponseBase<MakeMoneyIndexResponseV3> model) {

                            if (model.getCode() == 600 && model.getSucc() == 1) {
                                receiveBt.setText(getActivity().getResources().getString(R.string.makemoney_t19_str));
                                receiveBt.setEnabled(false);
                                getMoneyRanking();
                                showMsgDialog();
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                            }
                            ToastUtils.getInstance(getActivity()).showToastSystem(msg);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showMsgDialog() {
        final MessageDialog messageDialog = new MessageDialog(getActivity());
        messageDialog.show();
        messageDialog.setTitle(getResources().getString(R.string.comment_dialog_title_str));
        messageDialog.setMsg("已领取成功，请到钱包中查看!");
        messageDialog.setCancelBtn(getResources().getString(R.string.trevi_dialog_bt_str), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
            }
        });
        messageDialog.setOkBtn("查看钱包", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(getActivity(), MyApplication.cfgPlug.getValue_wallet_url_v2());
            }
        });
    }
}
